﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;

namespace kalkulator
{
    class Kalkulator
    {
		char[] operators = { '+', '*', '/', '-' };
        private Regex checker;
		private string input;
        private double first = 0;
        private double second = 0;
        private char operation = '0';
        private double result = 0;
        public double Result { 
            get {
                return this.result;
            }
        }
        public Kalkulator () {
			return;
		}
		public Kalkulator(string input)
		{
			this.input = input;
			this.generateChecker();
			if (checker.IsMatch(input))
			{
				this.parseInput();
				this.calculate();
			}
			else {
				MessageBox.Show("Podałeś formułę w niepoprawnym formacie!");
			}
		}
		private void generateChecker() {
			string digit = @"\-?\d+((\.|\,)\d+)?";
			string op = @"\"+this.operators[0].ToString();
			for(int i=1; i<this.operators.Length; i++) {
				op += @"|\"+this.operators[i].ToString();
			}
			string reg = @"^" + digit + "((" + op + ")" + digit + ")?$";
			this.checker = new Regex(@reg);
		}
		private void parseInput() {
			string worker = new string(this.input.ToCharArray());
			bool hasOperation = false;
			for (int i = 1; (i < worker.Length) && !hasOperation; i++) {
				if (this.operators.Contains(worker[i])) {
					hasOperation = true;
					this.operation = worker[i];
					worker = worker.Remove(i, 1);
					worker = worker.Insert(i, "?");
				}
			}
			string[] numbers = worker.Split('?');
			numbers[0] = numbers[0].Replace(',', '.');
			this.first = System.Convert.ToDouble(numbers[0], CultureInfo.InvariantCulture.NumberFormat);
			if (hasOperation)
			{
				numbers[1] = numbers[1].Replace(',', '.');
				this.second = System.Convert.ToDouble(numbers[1], CultureInfo.InvariantCulture.NumberFormat);
			}
			else {
				this.second = 0;
			}
		}
		private void calculate() {
			if (this.operation != '0')
			{
				switch (this.operation)
				{
					case '+': this.result = this.first + this.second; break;
					case '*': this.result = this.first * this.second; break;
					case '-': this.result = this.first - this.second; break;
					case '/':
						if (this.second != 0)
						{
							this.result = this.first / this.second;
						}
						else {
							if (this.first == 0)
							{
								MessageBox.Show("0/0 to symbol nieoznaczony");
							}
							else
							{

								MessageBox.Show("Nie dzielimy przez zero!");
							}
							this.result = 0;
						}
						break;
				}
			}
			else {
				this.result = this.first;
			}
		}
	}
}
